#include <stdio.h>
#define MAXSIZE 1024

struct Node{
	int Data;
	int Left;
	int Right;
};
void input(struct Node a[],int n){
	for( int i=0; i<n; i++ ){
		char c1,c2,c3;
		scanf(" %c %c %c",&c1,&c2,&c3);
		a[i].Data = c1;
		if( c2=='-' ) a[i].Left = -1;
		else a[i].Left = c2-'0';
		if( c3=='-' ) a[i].Right = -1;
		else a[i].Right = c3 -'0';
	}
}
int rootOfTree(struct Node a[],int len){
	char visit[len];
	for( int i=0; i<len; i++ ) visit[i] = 0;
	for(int i=0; i<len; i++ ){
		if( a[i].Left!=-1 ) visit[a[i].Left] = 1;
		if( a[i].Right!=-1 ) visit[a[i].Right] = 1;	
	} 
	for( int i=0; i<len; i++ )
		if( visit[i]==0 ) return i;
}
void insert(char tree[],struct Node a[],int p,int i){
	tree[i] = a[p].Data;
	if( a[p].Left!=-1 ) insert(tree,a,a[p].Left,i*2+1);
	if( a[p].Right!=-1 ) insert(tree,a,a[p].Right,i*2+2);
}
void createTree(struct Node a[],int root,int len,char tree[]){
	for( int i=0; i<MAXSIZE; i++ ) tree[i] = -1;
	insert(tree,a,root,0);
}
bool isSameConstruction(char treeA[],char treeB[]){
	bool ret = true;
	for( int i=0; i<32; i++ ){
		if( ( treeA[i*2+1]!=treeB[i*2+1] && treeA[i*2+1]!=treeB[i*2+2] ) &&
			( treeA[i*2+2]!=treeB[i*2+2] && treeA[i*2+2]!=treeB[i*2+1] ) ){
			printf("false %d\n", i);
			ret = false;
			break;
		}
	}
	return ret;
}
void output(char a[],int len){
	for( int i=0; i<len; i++ ){
		if( a[i]!=-1 ) printf("%c ",a[i]);
		else printf("- ");	
	} 
	printf("\n");
}
int main(){
	freopen("in.txt","r",stdin);
	int n;
	scanf("%d",&n);
	Node a[n],b[n];
	input(a,n);
	scanf("%d",&n);
	input(b,n);
	char treeA[MAXSIZE],treeB[MAXSIZE];
	createTree(a,rootOfTree(a,n),n,treeA);
	createTree(b,rootOfTree(b,n),n,treeB);
	printf("roota %d\nrootb %d\n",rootOfTree(a,n),rootOfTree(b,n));
	output(treeA,31);
	output(treeB,31);
	if( isSameConstruction(treeA,treeB) ) printf("Yes\n");
	else printf("No\n");
	return 0;
}
